<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>mongo概念 | 个人博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="一  安装mongohttps:&#x2F;&#x2F;www.mongodb.com&#x2F;docs&#x2F;manual&#x2F;tutorial&#x2F;install-mongodb-on-os-x&#x2F; brew services restart mongodb-community mongod  -》 http.server  将服务端启动起来了，用客户端来链接服务端  mongo的概念 数据库  show dbs显示所有的数据库，">
<meta property="og:type" content="article">
<meta property="og:title" content="mongo概念">
<meta property="og:url" content="https://gitee.com/wieldy/bailment-blog/2022/03/29/mongo%E6%A6%82%E5%BF%B5/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="一  安装mongohttps:&#x2F;&#x2F;www.mongodb.com&#x2F;docs&#x2F;manual&#x2F;tutorial&#x2F;install-mongodb-on-os-x&#x2F; brew services restart mongodb-community mongod  -》 http.server  将服务端启动起来了，用客户端来链接服务端  mongo的概念 数据库  show dbs显示所有的数据库，">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2022-03-29T14:12:00.000Z">
<meta property="article:modified_time" content="2023-04-23T12:11:43.652Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/bailment-blog/atom.xml" title="个人博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/bailment-blog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/bailment-blog/css/style.css">

  
    
<link rel="stylesheet" href="/bailment-blog/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/bailment-blog/" id="logo">个人博客</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/bailment-blog/">Home</a>
        
          <a class="main-nav-link" href="/bailment-blog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/bailment-blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/wieldy/bailment-blog"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-mongo概念" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/mongo%E6%A6%82%E5%BF%B5/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      mongo概念
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <ul>
<li>一</li>
</ul>
<h2 id="安装mongo"><a href="#安装mongo" class="headerlink" title="安装mongo"></a>安装mongo</h2><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/">https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/</a></p>
<p>brew services restart mongodb-community</p>
<p>mongod  -》 http.server</p>
<blockquote>
<p>将服务端启动起来了，用客户端来链接服务端</p>
</blockquote>
<h2 id="mongo的概念"><a href="#mongo的概念" class="headerlink" title="mongo的概念"></a>mongo的概念</h2><ul>
<li>数据库  show dbs显示所有的数据库，  use school</li>
<li>文档集合    db.createCollection(‘teachers’)</li>
<li>BSON 默认可以理解成就是一个个的json   <ul>
<li>db.teachers.insert()</li>
<li>db.teachers.find()</li>
<li>db.teachers.update()</li>
<li>db.teachers.remove()</li>
</ul>
</li>
</ul>
<h2 id="可视化工具"><a href="#可视化工具" class="headerlink" title="可视化工具"></a>可视化工具</h2><ul>
<li>Robo 3t  -&gt; studio 3t</li>
<li>navicat</li>
</ul>
<h2 id="curd"><a href="#curd" class="headerlink" title="curd"></a>curd</h2><ul>
<li>db.teachers.insert(插入的数据)</li>
<li>db.teachers.find(绝对的匹配，模糊的匹配, 显示什么)   {a:1,b,c:0} <ul>
<li>模式匹配符号  $or $ne $eq $lt $gt $lte $gte 正则</li>
</ul>
</li>
<li>db.teachers.update(查询条件,修改成什么样子)</li>
<li>db.teachers.remove()</li>
</ul>
<p>存嵌套的文档 而且没有关系的</p>
<h2 id="数据库的导出和备份"><a href="#数据库的导出和备份" class="headerlink" title="数据库的导出和备份"></a>数据库的导出和备份</h2><ul>
<li>mongoexport 导出的是什么格式的 json，csv格式</li>
<li>mongodump</li>
</ul>
<ul>
<li>二</li>
</ul>
<h2 id="什么是MongoDB"><a href="#什么是MongoDB" class="headerlink" title="什么是MongoDB"></a>什么是MongoDB</h2><blockquote>
<p>MongoDB是由C++编写的，基于分布式文件存储的NoSQL数据库。MongoDB中功能丰富是一个介于关系数据库和非关系数据库之间的产品。</p>
</blockquote>
<h2 id="MongoDB适用场景"><a href="#MongoDB适用场景" class="headerlink" title="MongoDB适用场景"></a>MongoDB适用场景</h2><ul>
<li>处理大量低价值的数据而且对处理性能有很高的要求</li>
<li>可以用mongoDB来实现数据的缓存 （缓存层）</li>
<li><h6 id="MongoDB搭建集群环境，实现存储数据横向扩展。"><a href="#MongoDB搭建集群环境，实现存储数据横向扩展。" class="headerlink" title="MongoDB搭建集群环境，实现存储数据横向扩展。"></a>MongoDB搭建集群环境，实现存储数据横向扩展。</h6></li>
</ul>
<h2 id="安装mongoDB"><a href="#安装mongoDB" class="headerlink" title="安装mongoDB"></a>安装mongoDB</h2><p><a target="_blank" rel="noopener" href="https://www.mongodb.com/">MongoDB官方网站</a></p>
<ul>
<li><p>在mac中安装<code>MongoDB</code></p>
<ul>
<li>Homebrew 的包管理器安装 MongoDB</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">brew tap mongodb/brew</span><br><span class="line">brew install mongodb-community@5.0</span><br><span class="line">brew services start mongodb-community@5.0 <span class="comment"># 后台运行</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>在windows中安装<code>MongoDB</code></p>
<ul>
<li>下载 <a target="_blank" rel="noopener" href="https://www.mongodb.com/try/download/community">msi</a> 安装 (不选择 <code>Install MongoDB Compass</code>)</li>
<li><em>mongo.exe</em> 客户端 、<em>mongod.exe</em> 、服务端 <em>mongos</em> 用于注册服务</li>
</ul>
</li>
</ul>
<blockquote>
<p>默认安装后<code>windows</code>是自启动使用27017端口， 我们在命令中输入 <code>mongod --version</code> 显示出对应安装信息则表示安装成功</p>
</blockquote>
<h2 id="Mongo可视化工具"><a href="#Mongo可视化工具" class="headerlink" title="Mongo可视化工具"></a>Mongo可视化工具</h2><ul>
<li><p>Robo 3T</p>
</li>
<li><p>Navicat</p>
</li>
</ul>
<h2 id="Mongo基本操作"><a href="#Mongo基本操作" class="headerlink" title="Mongo基本操作"></a>Mongo基本操作</h2><h3 id="1-链接数据库"><a href="#1-链接数据库" class="headerlink" title="1.链接数据库"></a>1.链接数据库</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mongo</span><br><span class="line">mongo --host <span class="string">&quot;mongod://xxx:27017&quot;</span> <span class="comment"># 链接到远程数据库</span></span><br></pre></td></tr></table></figure>

<h3 id="2-操作数据库"><a href="#2-操作数据库" class="headerlink" title="2.操作数据库"></a>2.操作数据库</h3><p>MongoDB是一个文档型数据结构。存储的数据是BSON (其实就是我们所谓的json格式) 比json包含更多的数据类型</p>
<ul>
<li>数据库  Database</li>
<li>集合  Collection （表）</li>
<li>文档  Document（数据）</li>
</ul>
<h4 id="1-操作数据库"><a href="#1-操作数据库" class="headerlink" title="1).操作数据库"></a>1).操作数据库</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">show dbs <span class="comment"># 显示全部数据库</span></span><br><span class="line">db <span class="comment"># 显示当前数据库</span></span><br><span class="line">use &lt;DataBaseName&gt; <span class="comment"># 切换到某个数据库中</span></span><br><span class="line">db.dropDatabase() <span class="comment"># 删除数据库</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>切换到某个数库中，像数据库中添加内容时才会创建对应的数据库。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="title function_">createUser</span>(&#123;<span class="attr">user</span>:<span class="string">&quot;jw&quot;</span>,<span class="string">&quot;pwd&quot;</span>:<span class="string">&quot;jw&quot;</span>,<span class="attr">roles</span>:[&#123;<span class="attr">role</span>:<span class="string">&quot;dbOwner&quot;</span>,<span class="string">&quot;db&quot;</span>:<span class="string">&quot;web&quot;</span>&#125;]&#125;)</span><br><span class="line">db.<span class="title function_">auth</span>() 登录用户</span><br><span class="line">db.<span class="property">student</span>.<span class="title function_">insert</span>(插入的对象) <span class="comment">// 插入数据</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">mongodump --db web --collection student --out backup</span><br><span class="line">mongorestore backup</span><br><span class="line"></span><br><span class="line">mongoexport -d web -c student --csv -f name,a -o a.<span class="property">csv</span> 到出具体格式</span><br><span class="line">mongoimport -d web -c student --type csv --file a.<span class="property">csv</span></span><br></pre></td></tr></table></figure>



<h4 id="2-操作集合"><a href="#2-操作集合" class="headerlink" title="2).操作集合"></a>2).操作集合</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">show collections # 显示所有集合</span><br><span class="line">db.&lt;collectionName&gt;,drop() # 删除集合</span><br></pre></td></tr></table></figure>

<h4 id="3-文档操作"><a href="#3-文档操作" class="headerlink" title="3).文档操作"></a>3).文档操作</h4><p>在集合中的文档数据结构可以不同的，但是在真正使用时我们还是期望结构是相同的，这样更方便操作存储的数据</p>
<h5 id="1-增加数据"><a href="#1-增加数据" class="headerlink" title="1.增加数据"></a>1.增加数据</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">use school;</span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">insert</span>(&#123;<span class="attr">name</span>:<span class="string">&quot;zs&quot;</span>,<span class="attr">age</span>:<span class="number">20</span>&#125;); <span class="comment">// 插入数据,自动增加_id字段</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里insert方法调用完毕后会返回插入的行数 ， 可以使用<code>insertOne</code>、<code>insertMany</code>插入成功后会返回插入的<code>id</code></p>
</blockquote>
<h5 id="2-查询数据"><a href="#2-查询数据" class="headerlink" title="2.查询数据"></a>2.查询数据</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(查询条件,显示的字段); <span class="comment">// 查询所有结果</span></span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;&#125; <span class="comment">/*查询所有*/</span>,&#123;<span class="attr">name</span>:<span class="number">1</span>&#125; <span class="comment">/*只显示name*/</span>)</span><br></pre></td></tr></table></figure>

<h5 id="3-查询匹配符"><a href="#3-查询匹配符" class="headerlink" title="3.查询匹配符$"></a>3.查询匹配符$</h5><p><strong>比较运算符</strong>:   <code>$gt</code> 、<code>$lt</code> 、<code>$in</code> 、<code>$ne</code>…</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">age</span>:&#123;<span class="attr">$gt</span>:<span class="number">20</span>&#125;&#125;) </span><br></pre></td></tr></table></figure>

<p><strong>逻辑运算符</strong>:  <code>$or</code>、<code>$not</code>…</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">$or</span>:[&#123;<span class="attr">age</span>:&#123;<span class="attr">$lt</span>:<span class="number">20</span>&#125;&#125;,&#123;<span class="attr">age</span>:<span class="number">33</span>&#125;]&#125;) <span class="comment">// 或者的关系</span></span><br></pre></td></tr></table></figure>

<h5 id="4-嵌套文档查询"><a href="#4-嵌套文档查询" class="headerlink" title="4.嵌套文档查询"></a>4.嵌套文档查询</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">insert</span>(&#123;<span class="attr">name</span>:<span class="string">&quot;jw&quot;</span>,<span class="attr">age</span>:<span class="number">30</span>,<span class="attr">address</span>:&#123;<span class="attr">num</span>:<span class="number">30</span>,<span class="attr">info</span>:<span class="string">&quot;回龙观&quot;</span>&#125;&#125;)</span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">address</span>:&#123;<span class="attr">info</span>:<span class="string">&quot;回龙观&quot;</span>,<span class="attr">num</span>:<span class="number">30</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>插入的顺序和查询的顺序不一致则无法正常查询到数据，所以一般不会这样进行嵌套文档查询</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="string">&quot;address.num&quot;</span>:<span class="number">30</span>,<span class="string">&quot;address.info&quot;</span>:<span class="string">&quot;回龙观&quot;</span>&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>切记这样才是正规套路</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">insert</span>(&#123;<span class="attr">name</span>:<span class="string">&quot;zry&quot;</span>,<span class="attr">age</span>:<span class="number">40</span>,<span class="attr">address</span>:&#123;<span class="attr">num</span>:<span class="number">40</span>,<span class="attr">info</span>:<span class="string">&quot;回龙观&quot;</span>&#125;,<span class="attr">hobby</span>:[<span class="string">&#x27;drink&#x27;</span>,<span class="string">&#x27;eat&#x27;</span>]&#125;)</span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">hobby</span>:&#123;<span class="attr">$all</span>:[<span class="string">&#x27;eat&#x27;</span>,<span class="string">&#x27;drink&#x27;</span>]&#125;&#125;); <span class="comment">// 查询数组中包含的项</span></span><br><span class="line">db.<span class="property">teachers</span>.<span class="title function_">find</span>(&#123;<span class="attr">hobby</span>:&#123;<span class="attr">$size</span>:<span class="number">2</span>&#125;&#125;); <span class="comment">// 查询数组中包含的项</span></span><br></pre></td></tr></table></figure>

<h5 id="5-更新文档"><a href="#5-更新文档" class="headerlink" title="5.更新文档"></a>5.更新文档</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">update</span>(&#123;<span class="attr">name</span>:<span class="string">&#x27;zs&#x27;</span>&#125;,&#123;<span class="attr">$set</span>:&#123;<span class="attr">age</span>:<span class="number">0</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>更新时需要增添$set属性否则会直接覆盖查到的文档</p>
</blockquote>
<h5 id="6-删除文档"><a href="#6-删除文档" class="headerlink" title="6.删除文档"></a>6.删除文档</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.<span class="property">teachers</span>.<span class="title function_">deleteOne</span>(&#123;<span class="attr">name</span>:<span class="string">&#x27;zs&#x27;</span>&#125;); <span class="comment">// 删除某个文档</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>可以通过deleteMany删除多条匹配到的文档</p>
</blockquote>
<h2 id="Mongoose的使用"><a href="#Mongoose的使用" class="headerlink" title="Mongoose的使用"></a>Mongoose的使用</h2><ul>
<li>orm工具方便，而且可以约束存储的内容 </li>
<li><a target="_blank" rel="noopener" href="https://mongoosejs.com/docs/guide.html">文档地址</a></li>
</ul>
<h3 id="1-链接数据库-1"><a href="#1-链接数据库-1" class="headerlink" title="1.链接数据库"></a>1.链接数据库</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mongoose = <span class="built_in">require</span>(<span class="string">&#x27;mongoose&#x27;</span>);</span><br><span class="line">mongoose.<span class="title function_">connect</span>(<span class="string">`mongodb://127.0.0.1:27017/school`</span>, &#123;</span><br><span class="line">    <span class="attr">useNewUrlParser</span>: <span class="literal">true</span>,</span><br><span class="line">    <span class="attr">useUnifiedTopology</span>: <span class="literal">true</span></span><br><span class="line">&#125;, <span class="keyword">function</span>(<span class="params">err</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;数据库链接失败&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;链接数据库成功&#x27;</span>)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="2-创建Schema"><a href="#2-创建Schema" class="headerlink" title="2.创建Schema"></a>2.创建Schema</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">UserSchema</span> = mongoose.<span class="title class_">Schema</span>(&#123;</span><br><span class="line">    <span class="attr">username</span>:&#123;  <span class="comment">// vue-&gt; props校验</span></span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">String</span>,</span><br><span class="line">        <span class="attr">trim</span>:<span class="literal">true</span>, <span class="comment">// 表示去掉前后空格</span></span><br><span class="line">        <span class="attr">lowercase</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="attr">required</span>:<span class="literal">true</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">password</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">String</span>, <span class="comment">// 当保存密码的时候</span></span><br><span class="line">        <span class="attr">required</span>:<span class="literal">true</span>,</span><br><span class="line">        <span class="attr">validate</span>:&#123;</span><br><span class="line">            <span class="title function_">validator</span>(<span class="params">value</span>)&#123; <span class="keyword">return</span> <span class="literal">true</span> &#125;<span class="comment">// 返回true表示校验通过</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">age</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">Number</span>,</span><br><span class="line">        <span class="attr">default</span>:<span class="number">6</span>,</span><br><span class="line">        <span class="attr">min</span>:<span class="number">0</span>,</span><br><span class="line">        <span class="attr">max</span>:<span class="number">120</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">gender</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:<span class="title class_">Number</span>,</span><br><span class="line">        <span class="attr">enum</span>:[<span class="number">0</span>,<span class="number">1</span>]</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;,&#123;</span><br><span class="line">    <span class="attr">timestamps</span>:&#123;</span><br><span class="line">        <span class="attr">createAt</span>:<span class="string">&#x27;createAt&#x27;</span>,</span><br><span class="line">        <span class="attr">updateAt</span>:<span class="string">&#x27;updateAt&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="3-创建模型"><a href="#3-创建模型" class="headerlink" title="3.创建模型"></a>3.创建模型</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">UserModel</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;User&#x27;</span>,<span class="title class_">UserSchema</span>,<span class="string">&#x27;user&#x27;</span>);</span><br></pre></td></tr></table></figure>



<h3 id="4-创建数据"><a href="#4-创建数据" class="headerlink" title="4.创建数据"></a>4.创建数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">    arr.<span class="title function_">push</span>(&#123; <span class="attr">username</span>: <span class="string">&quot;zs&quot;</span> + i, <span class="attr">password</span>: <span class="string">&quot;abc&quot;</span> + i, <span class="attr">age</span>: i, <span class="attr">gender</span>: <span class="number">0</span> &#125;)</span><br><span class="line">&#125;</span><br><span class="line">;(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> users =  <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">create</span>(arr);</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(); <span class="comment">// 断开链接</span></span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>



<h3 id="5-查询数据"><a href="#5-查询数据" class="headerlink" title="5.查询数据"></a>5.查询数据</h3><h4 id="1-基本查询"><a href="#1-基本查询" class="headerlink" title="1.基本查询"></a>1.基本查询</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> users = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">find</span>(&#123;</span><br><span class="line">        <span class="attr">$or</span>: [&#123; <span class="attr">username</span>: <span class="string">&#x27;zs1&#x27;</span> &#125;, &#123; <span class="attr">username</span>: <span class="string">&#x27;zs4&#x27;</span> &#125;]</span><br><span class="line">    &#125;, &#123; <span class="attr">age</span>: <span class="number">1</span>, <span class="attr">name</span>: <span class="number">1</span> &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(users);</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(); <span class="comment">// 断开链接</span></span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h4 id="2-分页查询"><a href="#2-分页查询" class="headerlink" title="2.分页查询"></a>2.分页查询</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> limit = <span class="number">3</span>;</span><br><span class="line"><span class="keyword">const</span> currentPage = <span class="number">2</span>;</span><br><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> users = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">find</span>(&#123;&#125;).<span class="title function_">skip</span>((currentPage - <span class="number">1</span>) * limit).<span class="title function_">limit</span>(limit).<span class="title function_">sort</span>(&#123; <span class="attr">age</span>: -<span class="number">1</span> &#125;)</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(users);</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>();</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>

<h4 id="3-关联查询"><a href="#3-关联查询" class="headerlink" title="3.关联查询"></a>3.关联查询</h4><p>创建文章集合，存储时让用户关联文章数据</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleSchema</span> = <span class="keyword">new</span> mongoose.<span class="title class_">Schema</span>(&#123;</span><br><span class="line">    <span class="attr">title</span>: <span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">content</span>: <span class="title class_">String</span>,</span><br><span class="line">    <span class="attr">createTime</span>: &#123;</span><br><span class="line">        <span class="attr">type</span>: <span class="title class_">Date</span>,</span><br><span class="line">        <span class="attr">default</span>: <span class="title class_">Date</span>.<span class="property">now</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">user_id</span>:&#123;</span><br><span class="line">        <span class="attr">type</span>:mongoose.<span class="property">SchemaTypes</span>.<span class="property">ObjectId</span>,</span><br><span class="line">        <span class="attr">ref</span>:<span class="string">&#x27;User&#x27;</span></span><br><span class="line">    &#125; <span class="comment">// 用户的_id 类型就是ObjectId</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ArticleModel</span> = mongoose.<span class="title function_">model</span>(<span class="string">&#x27;Article&#x27;</span>, <span class="title class_">ArticleSchema</span>,<span class="string">&#x27;article&#x27;</span>);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> user = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">create</span>(&#123; <span class="attr">username</span>: <span class="string">&#x27;jw&#x27;</span>, <span class="attr">password</span>: <span class="string">&#x27;jw&#x27;</span> &#125;);</span><br><span class="line">    <span class="keyword">let</span> article =<span class="keyword">await</span> <span class="title class_">ArticleModel</span>.<span class="title function_">create</span>(&#123; <span class="attr">title</span>: <span class="string">&#x27;MongoDB&#x27;</span>, <span class="attr">content</span>: <span class="string">&#x27;如何使用&#x27;</span>, <span class="attr">user_id</span>: user.<span class="property">_id</span> &#125;);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(article);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h5 id="3-1-populate"><a href="#3-1-populate" class="headerlink" title="3.1 populate"></a>3.1 <code>populate</code></h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">let</span> r = <span class="keyword">await</span> <span class="title class_">ArticleModel</span>.<span class="title function_">findById</span>(<span class="string">&#x27;61b32f1ab860e70c9836efcc&#x27;</span>).<span class="title function_">populate</span>(<span class="string">&#x27;user_id&#x27;</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(r);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h5 id="3-2-aggregate"><a href="#3-2-aggregate" class="headerlink" title="3.2 aggregate"></a>3.2 aggregate</h5><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> r = <span class="keyword">await</span> <span class="title class_">ArticleModel</span>.<span class="title function_">aggregate</span>([</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">$lookup</span>:&#123;</span><br><span class="line">            <span class="attr">from</span>:<span class="string">&#x27;user&#x27;</span>, <span class="comment">// 通过文章 查询用户</span></span><br><span class="line">            <span class="attr">localField</span>:<span class="string">&#x27;user_id&#x27;</span>, <span class="comment">// 通过文章的localField 关联foreginFiled</span></span><br><span class="line">            <span class="attr">foreignField</span>:<span class="string">&quot;_id&quot;</span>,</span><br><span class="line">            <span class="attr">as</span>:<span class="string">&#x27;user&#x27;</span> <span class="comment">// 查到的结果 放到user字段中</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">$match</span>:&#123;</span><br><span class="line">            <span class="attr">_id</span>:mongoose.<span class="property">Types</span>.<span class="title class_">ObjectId</span>(<span class="string">&#x27;61b32f1ab860e70c9836efcc&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="attr">$project</span>:&#123; <span class="comment">// 和我们写的populate第二个参数功能一样,只显示用户的字段</span></span><br><span class="line">            <span class="attr">user</span>:<span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">/*&#123;  根据字段进行分组</span></span><br><span class="line"><span class="comment">         $group:&#123;</span></span><br><span class="line"><span class="comment">             _id:&#x27;$username&#x27;,</span></span><br><span class="line"><span class="comment">             age:&#123;$sum:&quot;$age&quot;&#125;</span></span><br><span class="line"><span class="comment">         &#125;</span></span><br><span class="line"><span class="comment">     &#125;*/</span></span><br><span class="line">])</span><br></pre></td></tr></table></figure>

<h3 id="6-修改数据"><a href="#6-修改数据" class="headerlink" title="6.修改数据"></a>6.修改数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> doc = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">updateOne</span>(&#123; <span class="attr">username</span>: <span class="string">&#x27;111&#x27;</span> &#125;, &#123; <span class="attr">username</span>: <span class="string">&#x27;xxx&#x27;</span> &#125;, &#123; <span class="attr">upsert</span>: <span class="literal">true</span> &#125;)</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>();</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>

<h3 id="7-删除数据"><a href="#7-删除数据" class="headerlink" title="7.删除数据"></a>7.删除数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> r = <span class="keyword">await</span> <span class="title class_">UserModel</span>.<span class="title function_">deleteOne</span>(&#123;<span class="attr">username</span>:<span class="string">&#x27;xxx&#x27;</span>&#125;)</span><br><span class="line">    mongoose.<span class="title function_">disconnect</span>(r);</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>

<h2 id="Mongoose扩展"><a href="#Mongoose扩展" class="headerlink" title="Mongoose扩展"></a>Mongoose扩展</h2><h3 id="1-模型扩展"><a href="#1-模型扩展" class="headerlink" title="1.模型扩展"></a>1.模型扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">UserSchema</span>.<span class="property">statics</span>.<span class="property">findByName</span> = <span class="keyword">function</span> (<span class="params">username</span>) &#123; <span class="comment">// 相当于在模型上直接扩展方法</span></span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">findOne</span>(&#123;username&#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">UserModel</span>.<span class="title function_">findByName</span>(<span class="string">&quot;jw&quot;</span>); </span><br></pre></td></tr></table></figure>

<h3 id="2-实例扩展"><a href="#2-实例扩展" class="headerlink" title="2.实例扩展"></a>2.实例扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">UserSchema</span>.<span class="property">methods</span>.<span class="property">saveMd5</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">password</span> = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>).<span class="title function_">createHash</span>(<span class="string">&#x27;md5&#x27;</span>).<span class="title function_">update</span>(<span class="variable language_">this</span>.<span class="property">password</span>).<span class="title function_">digest</span>(<span class="string">&#x27;base64&#x27;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="title function_">save</span>();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">new</span> <span class="title class_">UserModel</span>(&#123;<span class="attr">username</span>:<span class="string">&#x27;zf&#x27;</span>,<span class="attr">password</span>:<span class="string">&#x27;123&#x27;</span>&#125;).<span class="title function_">save</span>();</span><br></pre></td></tr></table></figure>

<h3 id="3-插件扩展"><a href="#3-插件扩展" class="headerlink" title="3.插件扩展"></a>3.插件扩展</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">plugin</span>(<span class="params">schema,options</span>)&#123; <span class="comment">// 将方法进行了封装</span></span><br><span class="line">    schema.<span class="title function_">virtual</span>(<span class="string">&#x27;usernameAndAge&#x27;</span>).<span class="title function_">get</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">username</span> + <span class="string">&quot;:&quot;</span> + <span class="variable language_">this</span>.<span class="property">password</span></span><br><span class="line">    &#125;); <span class="comment">// 提取公共逻辑</span></span><br><span class="line">    schema.<span class="title function_">pre</span>(<span class="string">&#x27;save&#x27;</span>,<span class="keyword">function</span> (<span class="params">next</span>) &#123; </span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(options);</span><br><span class="line">        <span class="title function_">next</span>(); <span class="comment">// 之前 格式化数据  之后 一般都是存储日志 后续操作</span></span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="title class_">UserSchema</span>.<span class="title function_">plugin</span>(plugin,&#123;<span class="attr">a</span>:<span class="number">1</span>&#125;); </span><br></pre></td></tr></table></figure>


      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/mongo%E6%A6%82%E5%BF%B5/" data-id="cljmgj1ey000lzc9j6rd06208" data-title="mongo概念" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/bailment-blog/2022/03/29/mongo/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          mongo
        
      </div>
    </a>
  
  
    <a href="/bailment-blog/2022/03/29/node/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">node</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/07/">July 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/06/">June 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/04/">April 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/03/">March 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2022/03/">March 2022</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/bailment-blog/2023/07/03/%E5%B7%A5%E4%BD%9C%E6%97%A5%E5%BF%97/">工作日志</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/29/payMent/">payMent</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/20/%E7%BD%91%E7%BA%A2%E9%9D%A2%E8%AF%95%E9%A2%98/">原理题</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/19/%E5%89%8D%E7%AB%AF%E5%A4%A7%E5%B1%8F%E8%87%AA%E9%80%82%E5%BA%94%E6%96%B9%E6%B3%95/">前端大屏自适应方法</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/17/10%E4%B8%AAJavaScript%E5%B8%B8%E8%A7%81%E9%AB%98%E7%BA%A7%E7%9F%A5%E8%AF%86%E7%82%B9/">10个JavaScript常见高级知识点</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 John Doe<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/bailment-blog/" class="mobile-nav-link">Home</a>
  
    <a href="/bailment-blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/bailment-blog/js/jquery-3.4.1.min.js"></script>



  
<script src="/bailment-blog/fancybox/jquery.fancybox.min.js"></script>




<script src="/bailment-blog/js/script.js"></script>





  </div>
</body>
</html>